using System;
using Microsoft.SPOT;

namespace nRF24L10P.Register
{
    public abstract class RegisterBase
    {
        private byte[] valueBuffer;
        public byte[] Value
        {
            get
            {
                return valueBuffer;
            }
            internal
            set
            {
                valueBuffer = value;
            }
        }

        protected   byte firstByte
        {
            get
            {
                return valueBuffer[0];
            }
            set
            {
                valueBuffer[0] = value;
            }
        }
        public int Length { get; private set; }
        public byte Address { get; private set; }
        //protected byte firstByte;
        protected nRF24L10P device;
        protected RegisterBase(nRF24L10P device, int length, byte address)
        {
            this.device = device;
            Length = length;
            Value = new byte[length];
            Address = address;
        }

        public void Load()
        {
            Value = device.SpiReadWrite(SPICommands.R_REGISTER, Address, Value);
        }

        public void Save()
        {
            device.SpiReadWrite(SPICommands.W_REGISTER, Address, Value);
        }

        public static implicit operator byte[](RegisterBase source)
        {
            return source.Value;
        }

        public static implicit operator byte(RegisterBase source)
        {
            if (source.Length == 1)
            {
                return source.Value[0];
            }
            else
            {
                throw new InvalidOperationException("cannot convert register value to single byte while register length is greater than 1");
            }
        }

    }
}
